package com.example.user.controller;

import com.example.common.response.PageResponse;
import com.example.common.util.CustomJWTUtil;
import com.example.user.entity.User;
import com.example.user.request.LoginRequest;
import com.example.user.request.SendCodeRequest;
import com.example.user.request.UserListRequest;
import com.example.user.request.UserRequest;
import com.example.common.response.R;
import com.example.user.response.LoginResponse;
import com.example.user.response.UserResponse;
import com.example.user.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    CustomJWTUtil customJWTUtil;

    @GetMapping("count")
    public R<Long> count() {
        return R.ok(userService.count());
    }

    @PostMapping("register")
    public R<Long> register(@RequestBody @Valid UserRequest request) {
        return R.ok(userService.register(request));
    }

    @PostMapping("send-code")
    public R<Long> sendCode(@Valid @RequestBody SendCodeRequest request) {
        userService.sendCode(request);
        return R.ok();
    }

    @PostMapping({"login", "admin-login"})
    public R<LoginResponse> login(@Valid @RequestBody LoginRequest request, HttpServletRequest servletRequest) {
        boolean isAdminLogin = servletRequest.getRequestURI().endsWith("admin-login");

        LoginResponse loginResponse = userService.login(request, isAdminLogin);

        String token = customJWTUtil.createToken(loginResponse.getId(), loginResponse.getMobile(), isAdminLogin);
        loginResponse.setToken(token);

        return R.ok(loginResponse);
    }

    @GetMapping("list")
    public R<PageResponse<UserResponse>> list(@Valid UserListRequest request) {
        PageResponse<UserResponse> list = userService.list(request);
        return R.ok(list);
    }
}
